import 'package:flutter/material.dart';
import 'package:flutter_create_framework/generated/l10n.dart';
import 'package:flutter_create_framework/provider/state_provider.dart';
import 'package:flutter_create_framework/util/location_storge_util.dart';
import 'package:provider/provider.dart';

class SettingPort extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final _formKey = GlobalKey<FormState>();
    String port;

    return Scaffold(
      appBar: AppBar(
        title: Text(S.of(context).server_port),
        actions: <Widget>[
          IconButton(icon: Icon(Icons.check), onPressed: ()async{
            if(_formKey.currentState.validate()){
              _formKey.currentState.save();
              await LocationStrogeUtil().set("port", port);
              context.read<StateProvider>().setPort(port);
              Navigator.of(context).pop();
            }
          })
        ],
      ),
      body: Padding(
        padding: EdgeInsets.all(16),
        child: Form(
          child: Column(
            children: <Widget>[
              TextFormField(
                initialValue: context.watch<StateProvider>().port,
                decoration:
                    InputDecoration(
                        labelText: S.of(context).server_port,
                    ),
                keyboardType: TextInputType.number,
                onSaved: (value) {
                  port = value;
                },
                validator: (String value) {
                  try{
                    int.parse(value);
                    return value.length > 0 &&
                        int.parse(value) > 0 &&
                        int.parse(value) < 65535
                        ? null
                        : S.of(context).server_port_warning;
                  }catch(e){
                    return S.of(context).server_port_warning;
                  }
                },
              )
            ],
          ),
          key: _formKey,
          autovalidate: true,
        ),
      ),
    );
  }
}
